#!/bin/env python3
# -*- coding:utf-8 -*-
"""
    [模块名]
    Add By : cdj <e4ting@qq.com> 2021-09-23 09:00:01
"""
import sys,os
import json,time
from pdb import set_trace as strace
from traceback  import format_exc as dumpstack
from textwrap import dedent
from click    import style

from e4ting import log,util
# from e4ting.cache.cache import INRC

# from . import export,WampUtil
# from .models import ModelResults,ModelCards,flush
import itertools
from random import shuffle
from queue import Queue

cards_names = ['♠A', '♠2', '♠3', '♠4', '♠5', '♠6', '♠7', '♠8', '♠9', '♠T', '♠J', '♠Q', '♠K', '♥A', '♥2', '♥3', '♥4', '♥5', '♥6', '♥7', '♥8', '♥9', '♥T', '♥J', '♥Q', '♥K', '♣A', '♣2', '♣3', '♣4', '♣5', '♣6', '♣7', '♣8', '♣9', '♣T', '♣J', '♣Q', '♣K', '♦A', '♦2', '♦3', '♦4', '♦5', '♦6', '♦7', '♦8', '♦9', '♦T', '♦J', '♦Q', '♦K']

colors_map = {
    "♠" : "s",
    "♥" : "h",
    "♣" : "c",
    "♦" : "d",
}

class Face():
    color_flag = True
    def __init__(self, uid=1):
        uid = int(uid)
        assert 0 <= uid <= len(cards_names)
        self.uid   = uid
        self.face = cards_names[ self.uid - 1 ]
        self.color,self.count = self.face[0],self.face[1]

    def webdump(self, hiden=False):
        # 是否隐藏牌面
        if hiden:
            return dict(type="back",
                  number=" ",
                   color=" ",
                    size=100)
        color = colors_map[self.color]
        return dict(type="face",
                  number=self.count,
                   color=color,
                    size=100)

    def __repr__(self):
        if not self.color_flag:
            return self.face
        if self.face[0] in "♥":
            return style(self.face, fg="bright_magenta")
        elif self.face[0] in "♦":
            return style(self.face, fg="bright_red")
        elif self.face[0] in "♣":
            return style(self.face, fg="blue")
        return self.face

class Cards():
    # 环形队列
    # cycle = itertools.cycle(["short"])
    cycle = itertools.cycle(["flush", "fs", "flush", "fs_r", "flush", "flush", "short", "flush"] )
    # new_id = INRC(attr="cards")

    def __init__(self, member=9, type=None):
        self.member = int(member)
        self.total  = 5 + self.member * 2
        self.data   = []
        self.init(type=type)

    def init(self, type=None):
        q = getattr(self, type or next(self.cycle))()
        self.common = [ q.get(), q.get(), q.get(), q.get(), q.get() ]
        self.players =[ [q.get(), q.get()] for i in range(self.member) ]
        # self.data   = [common, players]
        # self.save()

    def short(self):
        # 发短牌
        data = self.__short__()
        shuffle(data)
        shuffle(data)
        q = Queue()
        [ q.put(Face(i)) for i in data]
        return q

    def rand(self):
        data = list(range(1, 53))
        shuffle(data)
        shuffle(data)
        q = Queue()
        [ q.put(Face(i)) for i in data]
        return q

    def fs(self):
        # 同花顺
        data = self.__flush__()
        q = Queue()
        [ q.put(Face(i)) for i in data]
        return q

    def fs_r(self):
        # 反向同花顺
        data = self.__flush__()
        q = Queue()
        [ q.put(Face(i)) for i in data[::-1] ]
        return q

    def flush(self):
        # 同花
        data = list(self.__flush__()[:self.total+1])
        shuffle(data)
        q = Queue()
        [ q.put(Face(i)) for i in data]
        return q

    def __short__(self):
        # 短牌
        data = [ [i, i+13, i+2*13, i+3*13] for i in range(1, 10)]
        return [_ for i in data for _ in i]

    def __flush__(self):
        data = [
            range(1, 14),
            range(14, 27),
            range(27, 40),
            range(40, 53)
        ]
        shuffle(data)
        shuffle(data)
        return [_ for i in data for _ in i]

    @util.redef_return(ret=None)
    def save(self):
        self.uid = Cards.new_id
        data = { f"c{i+1}":int(card) for i,card in enumerate(self.common) }
        for _,p in enumerate(self.players):
            f1,f2 = p
            data[f"p{_+1}1"] = int(f1)
            data[f"p{_+1}2"] = int(f2)
        data["plays"] = len(self.players)
        ModelCards.create_and_return(uid=self.uid, **data)
        log.info(("局数：", self.uid))

    def dump(self):
        log.info(self.common)
        log.info(self.players)
        # strace()
        return ([ int(f) for f in self.common] , [ [int(f1), int(f2)] for f1,f2 in self.players])